function MyArray(capacity) {
    this.size = 0; // 数组已经存储个数
    this.array = new Array(capacity); // 初始化一个可以放 n 个元素的数组
}

MyArray.prototype.insert = function (index, element) {
    // 访问下标超出范围抛出异常
    if (index < 0 || index > this.size) {
        throw new Error('超出数组实际元素范围！');
    }

    // 超出数组容量上限，数组扩容
    if(this.size >= this.array.length) {
        this.resize();
    }
    // 从右向左循环，为要插入的元素腾开位置
    for (let i = this.size - 1; i >= index; i--) {
        this.array[i + 1] = this.array[i];
    }
    this.array[index] = element;
    this.size++;
}

MyArray.prototype.resize = function() {
    this.array = this.array.concat(new Array(this.array.length))
    console.log("resize", this.array);
}

MyArray.prototype.delete = function(index) {
    // 访问下标超出范围抛出异常
    if (index < 0 || index > this.size) {
        throw new Error('超出数组实际元素范围！');
    }
    const deletedElement = this.array[index];
    // 此处需要 <= ，当移到最后一项时置为 undefined
    for (let i = index; i <= this.size - 1; i++) {
        this.array[i] = this.array[i + 1];
    }
    this.size--;
    return deletedElement;
}

MyArray.prototype.output = function() {
    for (let i=0; i < this.size; i++) {
        console.log(this.array[i]);
    }
}

let myArray = new MyArray(4)
myArray.insert(0,3);
myArray.insert(1,7);
myArray.insert(2,9);
myArray.insert(3,5);
myArray.insert(1,6); // 测试扩容
myArray.insert(5,8);
myArray.delete(3);
// myArray.insert(8, 10) // 测试插入超出数组范围
// myArray.delete(8) // 测试删除超出数组范围
myArray.output()

